import {
  Mesh,
  TextureLoader,
  MeshBasicMaterial,
  SphereBufferGeometry,
  Matrix4,
} from "three";

export function clampToMaxSize(image, maxSize) {
  if (image.width > maxSize || image.height > maxSize) {
    var scale = maxSize / Math.max(image.width, image.height);

    var canvas = document.createElement("canvas");
    canvas.width = Math.floor(image.width * scale);
    canvas.height = Math.floor(image.height * scale);

    var context = canvas.getContext("2d");
    context.drawImage(
      image,
      0,
      0,
      image.width,
      image.height,
      0,
      0,
      canvas.width,
      canvas.height
    );

    return canvas;
  }

  return image;
}

const cache = {};

export function getTexture(url, maxSize) {
  return new Promise((res) => {
    if (cache[url]) {
      res(cache[url]);
      return;
    }

    let textTure;

    // 第一种方式获取
    textTure = new TextureLoader().load(
      url,
      (texture) => {
        maxSize && (textTure.image = clampToMaxSize(texture.image, maxSize));
        cache[url] = textTure;
        res(textTure);
      },
      () => {},
      () => {
        console.log("图片【" + url + "】下载错误");
        cache[url] = textTure;
        res(textTure);
      }
    );
  });
}

export const getSkyBox = async (url) => {
  const texture = await getTexture(url);
  const material = new MeshBasicMaterial({ map: texture });
  const SkyBoxSize = 4000;
  const skyBox = new Mesh(
    new SphereBufferGeometry(SkyBoxSize, 32, 32),
    material
  );
  skyBox.applyMatrix(new Matrix4().makeScale(1, 1, -1));
  return skyBox;
};
